package com.gujiayue.module.sys.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gujiayue.common.utils.StringUtils;
import com.gujiayue.module.sys.dao.SysPrivilegeRoleDao;
import com.gujiayue.module.sys.dao.SysRoleDao;
import com.gujiayue.module.sys.dao.SysUsrDao;
import com.gujiayue.module.sys.pojo.SysPrivilegeRoleDo;
import com.gujiayue.module.sys.pojo.SysRoleDo;
import com.gujiayue.module.sys.pojo.SysRoleUsr;
import com.gujiayue.module.sys.pojo.SysUsrDo;
import com.gujiayue.module.sys.pojo.copier.AuthCopier;
import com.gujiayue.module.sys.service.SecurityService;

@Service
@Transactional(readOnly = true)
public class SecurityServiceImpl implements SecurityService {

	@Resource
	private SysUsrDao sysUsrDao;

	@Resource
	private SysRoleDao sysRoleDao;

	@Resource
	private SysPrivilegeRoleDao sysPrivilegeRoleDao;

	@Override
	public SysUsrDo loadUserByUsername(String username) throws UsernameNotFoundException {
		if (StringUtils.isBlank(username)) {
			throw new RuntimeException("用户不能为空");
		}
		// 根据用户名查询用户
		SysUsrDo sysUsrDo = sysUsrDao.loadUserByUsername(SysUsrDo.builder().loginName(username).build());
		if (StringUtils.isEmpty(sysUsrDo)) {
			throw new RuntimeException("用户不存在");
		}
		SysRoleUsr roleUsr=AuthCopier.INSTANCE.copierSysRoleUsr(sysUsrDo);
		// 获取角色信息
		List<SysRoleDo> roleList = sysRoleDao.getUserRoleList(roleUsr);
		//默认通用角色
		if (roleList.size() <=0) {
			roleList.add(new SysRoleDo("Y0000"));
		}
		sysUsrDo.setRoleList(roleList);
		return sysUsrDo;
	}

	@Override
	public List<SysPrivilegeRoleDo> getPrivilegeRoleList() {
		return sysPrivilegeRoleDao.getPrivilegeRoleList();
	}

}
